package com.teachoa.bean;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.teachoa.enumtype.ModuleEnum;
import com.teachoa.util.IDUtil;
import com.teachoa.util.Lists;
import com.teachoa.util.Maps;

@SuppressWarnings({"rawtypes", "unchecked"})
public class Menu extends Model<Menu> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2991757243377064927L;
	
	public static final Menu dao = new Menu();
	
	public List<Menu> getMenusByType(int type) {
		String sql = "select a.* from menu a left join role_menu b on a.id = b.menu_id where b.type = ?"
				+ " order by module,orderby ";
		return dao.find(sql, new Object[]{type});
	}
	
	public Map getMenuTree(int type) {
		List<Menu> menuList = getMenusByType(type);
		Map map = new LinkedHashMap();
		for(Menu menu:menuList) {
			int module = menu.getInt("module");
			String moduleName = ModuleEnum.getEnumByCode(module).getDesc();
			if(!map.containsKey(moduleName)) {
				map.put(moduleName, Lists.newArrayList(menu));
			} else {
				((List)map.get(moduleName)).add(menu);
			}
		}
		return map;
	}
	
	public Menu findByName(String name) {
		String sql = "select * from menu where name = ?";
		return dao.findFirst(sql, new Object[]{name});
	}
	
	public void createMenu() {
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "字典管理", "url", "/dict", "module", 1, "orderby", 1));
		dao.save();
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "系统信息发布管理", "url", "/sysmsg", "module", 1, "orderby", 2));
		dao.save();
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "用户管理", "url", "/user", "module", 2, "orderby", 1));
		dao.save();
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "教师学生管理", "url", "/teach", "module", 3, "orderby", 2));
		dao.save();
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "项目管理", "url", "/project", "module", 4, "orderby", 2));
		dao.save();
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "项目信息发布管理", "url", "/publish", "module", 4, "orderby", 2));
		dao.save();
		dao.setAttrs(Maps.newHashMap("id", IDUtil.getId(), "name", "项目咨询管理", "url", "/consult", "module", 4, "orderby", 2));
		dao.save();
	}

}
